package com.server.questionbank.snframe.service.CourseService.Impl.Resource;

import com.server.questionbank.snframe.domain.Course.Resource.CourseFiles;
import com.server.questionbank.snframe.domain.Course.Result.CourseResourceInfo;
import com.server.questionbank.snframe.mapper.Course.Resource.CourseFilesMapper;
import com.server.questionbank.snframe.service.CourseService.Resource.CourseFileService;
import com.server.questionbank.snframe.util.FileUtil.MinIoUtil;
import com.server.questionbank.snframe.util.MinIo.MinIoBucket;
import com.server.questionbank.snframe.util.MinIo.MinIoFactory;
import io.minio.StatObjectResponse;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.List;

@Service
public class CourseFileServiceImpl implements CourseFileService {
    @Autowired
    private MinIoFactory minIoFactory;

    @Autowired
    private CourseFilesMapper courseFilesMapper;

    private String bucketName = "course";  // MinIO存储桶名称

    @Override
    public Boolean createFile(CourseFiles courseFiles) {
        return courseFilesMapper.insertFile(courseFiles) > 0;
    }

    @Override
    public Boolean updateFilePath(String filePath, Long fileId) {
        try {
            return courseFilesMapper.updateFilePath(filePath, fileId) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public CourseFiles getFileInfo(Long fileId) {
        return courseFilesMapper.getFileInfo(fileId);
    }

    @Override
    public List<CourseFiles> getFileListByResourceId(Long resourceId) throws Exception {
        MinIoBucket bucket = minIoFactory.openBucket(bucketName);
        List<CourseFiles> list = courseFilesMapper.getFileListByResourceId(resourceId).stream().map(resource -> {

            // 创建子类对象并拷贝基础字段
            CourseFiles courseFile = new CourseFiles();
            BeanUtils.copyProperties(resource, courseFile); // 需要Spring-beans依赖
            if (courseFile.getFilePath().isEmpty()) return courseFile;
            try {
                courseFile.setContentType(bucket.getFileType(courseFile.getFilePath()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return courseFile;
        }).toList();
        return list;
    }
}
